<?php
/**
* 方法汇总
* url 根入口 get_path_url
* 物理 get_path_root
* 检查是否是微信浏览器访问 is_wechat_browser()
* json 接口返回  function return_data($error_code=0,$error_msg='',$data=array())
* 格式化商品价格  price_format($price,$price_format=0, $change_price = true) {}
* 创建像这样的查询: "IN('a','b')";db_create_in
* 取汉字的第一个字的首字母 getFirstCharter
* 随机数 random()
* 写入文件 write_file
* 创建目录 mkdirs
* 读取目录 read_file
* post模拟浏览url post_data
* 分页 get_page_list
* 获得当前格林威治时间的时间戳 gmtime 本地时间 local_time
* 处理序列化的支付 unserialize_config
* 数组输出xml  array_toXml
* 当前IP real_ip
* cookie加密 encryption
* 获取header get_all_headers
* 机器随机数 randomFromDev
 */

  function home_url(){
    $menu_list = [
                  [
                      'name' => '浏览历史',
                      'route' => '../index/history',
                      'pic' => '../../images/history.png',
                  ],
                  [
                      'name' => '用户中心',
                      'route' => '../index/mypage',
                      'pic' => '../../images/me.png',
                  ],
                  [
                      'name' => '申请小店',
                      'route' => '../common/shop_form',
                      'pic' => '../../images/shop_on.png',
                  ],
                  [
                      'name' => '登录小店',
                      'route' => '../shop/login',
                      'pic' => '../../images/log-in.png',
                  ],
      ];
      return $menu_list;
  }
/**
 * 检查是否是微信浏览器访问
 */
function is_wechat_browser()
{
  $user_agent = $_SERVER['HTTP_USER_AGENT'];
  if (strpos($user_agent, 'MicroMessenger') === false) {
    return false;
  } else {
    return true;
  }
}

// 检测输入的验证码是否正确，$code为用户输入的验证码字符串
function check_verify($code, $id = '')
{
  $verify = new \Think\Verify();
  return $verify->check($code, $id);
}

//json 接口返回
function return_data($code = 0, $msg = '', $result = array())
{
  header('Content-Type: application/json');
  if (!$result) {
    $result = array();
  }

  $arr = array('code' => $code,'msg' => $msg,'result' => $result);

  echo(json_encode($arr));
  exit;
}

//url 根入口
function get_path_url()
{
  $url="http://".$_SERVER['HTTP_HOST'].__ROOT__.'/';
  return $url;
}

//根目录
function get_path_root()
{
  $RATH = dirname(dirname(dirname(dirname(__FILE__))));
  return $RATH;
}

/**
 * 获得当前格林威治时间的时间戳
 *
 * @return  integer
 */
function gmtime()
{
  return time();
}

/**
 * 获得用户的真实IP地址
 *
 * @access  public
 * @return  string
 */
function real_ip()
{
  static $realip = null;

  if ($realip !== null) {
    return $realip;
  }

  if (isset($_SERVER)) {
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
      $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

      /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
      foreach ($arr as $ip) {
        $ip = trim($ip);

        if ($ip != 'unknown') {
          $realip = $ip;

          break;
        }
      }
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
      $realip = $_SERVER['HTTP_CLIENT_IP'];
    } else {
      if (isset($_SERVER['REMOTE_ADDR'])) {
        $realip = $_SERVER['REMOTE_ADDR'];
      } else {
        $realip = '0.0.0.0';
      }
    }
  } else {
    if (getenv('HTTP_X_FORWARDED_FOR')) {
      $realip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif (getenv('HTTP_CLIENT_IP')) {
      $realip = getenv('HTTP_CLIENT_IP');
    } else {
      $realip = getenv('REMOTE_ADDR');
    }
  }

  preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
  $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

  return $realip;
}

/**
 * 输出xml字符
 * @throws WxPayException
**/
function array_to_xml($values)
{
  if (!is_array($values) || count($values) <= 0) {
    // throw new WxPayException("数组数据异常！");
    return false;
  }

  $xml = "<xml>";
  foreach ($values as $key=>$val) {
    if (empty($val)) {
      continue;
    }

    if (is_numeric($val)) {
      $xml.="<".$key.">".$val."</".$key.">";
    } else {
      $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
    }
  }
  $xml.="</xml>";
  return $xml;
}

/**
 * xml转数组的
 * @throws WxPayException
**/
function xml_to_array($xml)
{
  $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
  if (preg_match_all($reg, $xml, $matches)) {
    $count = count($matches[0]);
    for ($i = 0; $i < $count; $i++) {
      $subxml= $matches[2][$i];
      $key = $matches[1][$i];
      if (preg_match($reg, $subxml)) {
        $arr[$key] =xml_to_array($subxml);
      } else {
        $arr[$key] = $subxml;
      }
    }
  }
  return $arr;
}

function local_time($time = null)
{
  if ($time === null) {
    $time = gmtime();
  } elseif ($time <= 0) {
    return '';
  }

  return date("Y-m-d H:i", $time);
}

function format_datetime($datetime, $format = 'Y-m-d')
{
  if (!$datetime) {
    return false;
  }

  $time = strtotime($datetime);
  return date($format, $time);
}

/**
 * 格式化商品价格
 *
 * @access  public
 * @param   float   $price  商品价格
 * @return  string
 */
function price_format($price, $price_format=0, $change_price = true)
{
  $currency_format='￥%s';

  if ($price === '') {
    $price = 0;
  }
  $price = 0 + $price;//添加这一行，转换成数值
  if ($change_price) {
    switch ($price_format) {
  case 0:
  $price = number_format($price, 2, '.', '');
  break;
  case 1: // 保留不为 0 的尾数
  $price = preg_replace('/(.*)(\\.)([0-9]*?)0+$/', '\1\2\3', number_format($price, 2, '.', ''));
  if (substr($price, -1) == '.') {
    $price = substr($price, 0, -1);
  }
  break;
  case 2: // 不四舍五入，保留1位
  $price = substr(number_format($price, 2, '.', ''), 0, -1);
  break;
  case 3: // 直接取整
  $price = intval($price);
  break;
  case 4: // 四舍五入，保留 1 位
  $price = number_format($price, 1, '.', '');
  break;
  case 5: // 先四舍五入，不保留小数
  $price = round($price);
  break;
  }
  } else {
    $price = number_format($price, 2, '.', '');
  }

  return sprintf($currency_format, $price);
}

/**
 * 创建像这样的查询: "IN('a','b')";
 *
 * @access   public
 * @param    mix      $item_list      列表数组或字符串
 * @param    string   $field_name     字段名称
 *
 * @return   void
 */
function db_create_in($item_list, $field_name = '')
{
  if (empty($item_list)) {
    return $field_name . " IN ('') ";
  } else {
    if (!is_array($item_list)) {
      $item_list = explode(',', $item_list);
    }
    $item_list = array_unique($item_list);
    $item_list_tmp = '';
    foreach ($item_list as $item) {
      if ($item !== '') {
        $item_list_tmp .= $item_list_tmp ? ",'$item'" : "'$item'";
      }
    }
    if (empty($item_list_tmp)) {
      return $field_name . " IN ('') ";
    } else {
      return $field_name . ' IN (' . $item_list_tmp . ') ';
    }
  }
}

/**
 *
 * @param string $value 要加密的值
 * @param int $type     0加密  1解密
 */
function encryption($value, $type=0)
{
  $key=md5(C('ENCRYPTION_KEY'));
  if ($type==0) {
    $value=$key^$value;
    $value=  str_replace('=', '', base64_encode($value));
    return $value;
  } elseif ($type==1) {
    $value=  base64_decode($value);
    return $value^$key;
  }
}

//随机数
function random($length = 6, $numeric = 0)
{
  PHP_VERSION < '4.2.0' && mt_srand((double) microtime() * 1000000);
  if ($numeric) {
    $hash = sprintf('%0' . $length . 'd', mt_rand(0, pow(10, $length) - 1));
  } else {
    $hash = '';
    $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
    $max = strlen($chars) - 1;
    for ($i = 0; $i < $length; $i++) {
      $hash .= $chars[mt_rand(0, $max)];
    }
  }
  return $hash;
}

//写入文件日志
function write_file($file_name, $content, $path = "data/smslog")
{
  $RATH=dirname(dirname(dirname(dirname(__FILE__))))."/";
  $path.= '/'.date('Ymd')."/";

  mkdirs($RATH. $path);
  $filename = $RATH. $path . $file_name;

  $Ts = fopen($filename, "a+");
  fputs($Ts, "\r\n" . $content);
  fclose($Ts);
}

//检测创建目录
function mkdirs($dir, $mode = 0777)
{
  if (is_dir($dir) || @mkdir($dir, $mode)) {
    return true;
  }

  if (!mkdirs(dirname($dir), $mode)) {
    return false;
  }

  return @mkdir($dir, $mode);
}

//读取目录
function read_file($file_name, $path='/data/smslog')
{
  $RATH=dirname(dirname(dirname(dirname(__FILE__))))."/";
  $path.= '/' . date('Ymd')."/";

  $content = '';
  $filename =$RATH.$path.$file_name;

  if (function_exists('file_get_contents')) {
    @$content = file_get_contents($filename);
  } else {
    if (@$fp = fopen($filename, 'r')) {
      @$content = fread($fp, filesize($filename));
      @fclose($fp);
    }
  }
  $content = explode("\r\n", $content);
  return end($content);
}

//POST传递值
function post_data($url, $curlPost, $header='')
{
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, $url);

  if ($header) {
    curl_setopt($curl, CURLOPT_HEADER, 1);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  } else {
    curl_setopt($curl, CURLOPT_HEADER, false);
  }

  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_NOBODY, true);

  if ($curlPost) {
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
  }

  $return_str = curl_exec($curl);
  curl_close($curl);
  return $return_str;
}

function upload_file($upload_dir='image')
{
  $upload = new \Think\Upload();
  $upload->maxSize   =     3145728 ;
  // $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
  $upload->rootPath  =      './upload/'.$upload_dir.'/';
  $upload->savePath  =      '';
  $upload->subName  ='';
  $upload->replace = true;
  // $upload->subName = array('date','Ymd');

  mkdirs($upload->rootPath);
  // 上传文件
  $info   =   $upload->upload();
  foreach ($info as $key => $value) {
    if ($value['savename']) {
      $savename=$value['savename'];
    }
    if ($value['savepath']) {
      $savepath=$value['savepath'];
    }
  }

  if (!$info) {
    // 上传错误提示错误信息
    return array('error' => 1, 'message' =>$upload->getError());
  } else {
    // 上传成功 获取上传文件信息
    $str=$upload->rootPath.$savepath.$savename;
    return array('error' => 0, 'message' =>$str);
  }
}

function upload_image($f_name='', $upload_dir = 'images')
{
  add_file_postfix($f_name);

  $upload = new \Think\Upload();
  $upload->maxSize   =     3145728 ;
  $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');
  $upload->rootPath  =      './Uploads/'.$upload_dir.'/';
  $upload->savePath  =      '';
  $upload->subName  ='';

  // $upload->saveName = time();
  mkdirs($upload->rootPath);
  // 上传文件
  $info   =   $upload->uploadOne($_FILES[$f_name]);

  if (!$info) {// 上传错误提示错误信息
    return array('error' => 1, 'message' =>$upload->getError());
  } else {// 上传成功 获取上传文件信息

    $str='Uploads/'.$upload_dir.'/'.$info['savepath'].$info['savename'];
    return array('error' => 0, 'message' =>$str);
  }
}

//解决app 传送没后缀图片类型的问题
function add_file_postfix($name)
{
  if ($name) {
    $ftype=$_FILES[$name]['type'];
    $fname=$_FILES[$name]['name'];
    $ar_n=explode('.', $fname);

    if (!$ar_n[1]) {
      $ar_tp=explode('/', $ftype);
      $_FILES[$name]['name']=$fname.'.'.$ar_tp[1];
      return $_FILES[$name]['name'];
    }
  }

  return false;
}

/**
 * 格式化参数格式化成url参数
 */
function ToUrlParams($values)
{
  $buff = "";
  foreach ($values as $k => $v) {
    if (!is_array($v)) {
      $buff .= $k . "=" . $v . "&";
    }
  }

  $buff = trim($buff, "&");
  return $buff;
}

/* * ********************************************************
 * 基础函数库
 * ******************************************************** */

/**
 * 截取UTF-8编码下字符串的函数
 *
 * @param   string      $str        被截取的字符串
 * @param   int         $length     截取的长度
 * @param   bool        $append     是否附加省略号
 *
 * @return  string
 */
function sub_str($str, $length = 0, $append = true)
{
  $str = trim($str);
  $strlength = strlen($str);

  if ($length == 0 || $length >= $strlength) {
    return $str;
  } elseif ($length < 0) {
    $length = $strlength + $length;
    if ($length < 0) {
      $length = $strlength;
    }
  }

  if (function_exists('mb_substr')) {
    $newstr = mb_substr($str, 0, $length, 'utf8');
  } elseif (function_exists('iconv_substr')) {
    $newstr = iconv_substr($str, 0, $length, 'utf8');
  } else {
    //$newstr = trim_right(substr($str, 0, $length));
    $newstr = substr($str, 0, $length);
  }

  if ($append && $str != $newstr) {
    $newstr .= '...';
  }

  return $newstr;
}

/**
 * 处理序列化的支付、配送的配置参数
 * 返回一个以name为索引的数组
 *
 * @access  public
 * @param   string       $cfg
 * @return  void
 */
function unserialize_config($cfg)
{
  if (is_string($cfg) && ($arr = unserialize($cfg)) !== false) {
    $config = array();

    foreach ($arr as $key => $val) {
      $config[$val['name']] = $val['value'];
    }

    return $config;
  } else {
    return false;
  }
}

/**
 * 得到新订单号
 * @return  string
 */
function get_order_sn()
{
  /* 选择一个随机的方案 */
  mt_srand((double) microtime() * 1000000);

  return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}

/**
 * 获取自定义的header数据
 */
function get_all_headers()
{

  // 忽略获取的header数据
  $ignore = array('host','accept','content-length','content-type');

  $headers = array();

  foreach ($_SERVER as $key=>$value) {
    if (substr($key, 0, 5)==='HTTP_') {
      $key = substr($key, 5);
      $key = str_replace('_', ' ', $key);
      $key = str_replace(' ', '-', $key);
      $key = strtolower($key);

      if (!in_array($key, $ignore)) {
        $headers[$key] = $value;
      }
    }
  }

  return $headers;
}

/**
 * 读取/dev/urandom获取随机数
 * @param $len
 * @return mixed|string
 */
function randomFromDev($len)
{
  $fp = @fopen('/dev/urandom', 'rb');
  $result = '';
  if ($fp !== false) {
    $result .= @fread($fp, $len);
    @fclose($fp);
  } else {
    trigger_error('Can not open /dev/urandom.');
  }
  // convert from binary to string
  $result = base64_encode($result);
  // remove none url chars
  $result = strtr($result, '+/', '-_');

  return substr($result, 0, $len);
}

/**
* 本地图片上传拍又云
* @param $qrcode
* @return img|string
*/
function upload_yun($qrcode, $app_config)
{
  $upyun_config = $app_config;

  //TODO 上传到又拍云

  set_time_limit(0);
  ini_set('memory_limit', '512M');
  $process = curl_init($upyun_config['host']."/".$upyun_config['bucket']."/" . $qrcode);

  // 上传操作
  curl_setopt($process, CURLOPT_PUT, 1);
  curl_setopt($process, CURLOPT_USERPWD, $upyun_config['username'].":".$upyun_config['password']);
  curl_setopt($process, CURLOPT_HEADER, 0);
  curl_setopt($process, CURLOPT_TIMEOUT, 60);

  // 本地待上传的图片文件
  $local_file_path = '.' . $qrcode;
  $datas = fopen($local_file_path, 'r');
  fseek($datas, 0, SEEK_END);
  $file_length = ftell($datas);
  fseek($datas, 0);

  // 设置待上传图片的内容
  curl_setopt($process, CURLOPT_INFILE, $datas);

  // 设置待上传图片的长度
  curl_setopt($process, CURLOPT_INFILESIZE, $file_length);

  curl_setopt($process, CURLOPT_HTTPHEADER, array(
  //'x-gmkerl-type: fix_width',
  //'x-gmkerl-value: 200',
  'x-gmkerl-unsharp: true',
  'Mkdir:true',
  ));
  $str = curl_exec($process);
  curl_close($process);
  fclose($datas);

  $img = substr($qrcode, 1);
  $img = $upyun_config['endpoint'] ."/". $img;

  return $img;
}

function add_alipay_queue($order)
{
  vendor('php-resque.autoload');	// 引入队列类库
  $job = '\\Common\\Job\\AlipayJob'; // 定义任务类

  $field = "o.*,s.alipay_name as alipay_name,s.alipay_account as alipay_account,s.rate as rate,s.app_id as app_id";
  $orderinfo = M('Orders')->alias("o")->join("left join ".C("DB_PREFIX")."shops s on s.id=o.shop_id")
  ->field($field)->where("o.id={$order['id']}")->find();

  $args = array(
    'time' => gmtime(),
    'order' => $orderinfo,
  );

  if ($orderinfo['total_amount'] < C('alipay_maxamount')) {
    $jobId = \Resque::enqueue('default', $job, $args, true);
  }
}

function alipay_to_shop($order, $debug = false)
{
  if ($order['status'] != 7) {
    return false;
  }

  if ($order['is_payed'] == 2 || $order['alipay_account'] == "" || $order['alipay_name'] == "") {
    return false;
  }

  $app = M('Apps')->where("id=$order[app_id]")->find();

  $rsaPrivateKey = $app['alipay_rsaprivatekey'];
  $alipayrsaPublicKey = $app['alipay_rsapublickey'];
  $app_id = $app['alipay_appid'];

  if ($app['alipay_type'] == 2) {
    $gatewayUrl = 'https://openapi.alipay.com/gateway.do';
  } else {
    $gatewayUrl = 'https://openapi.alipaydev.com/gateway.do';
  }

  /*
  * sandbox沙箱环境用于测试  */
  $rsaPrivateKey = 'MIIEpAIBAAKCAQEA5D9sH6/yqxjwoPYn2YuZ6O1aL1MYTwVpZTfu2j5FOh4qSZAtZs7iE+MMRTULrfmYhT+hmgfhhS9kSbiC/PHonELj2R7FlviKEzaXwqzfiEGhL7t3tKmhk3uec8oRmkWYwn9Nmu0MNyLIVJjjYQn3hcB1QheJOhxbtsGOHgPrNxXxOlZ26k8WsBF+nmLuL/Wba3umYRYEP++5q3y3VZtpcCAqde62nuETW8nc0CTA0K/cxHFP63a2LAmLUJNIUQazp692o5Vicv+OCgMzdYFr/BON9lxVjBnWIJkUasyQM7feLNJapiXv4TmtR7sIaFjYSvqaFSmo5gbFwxhkvieNXQIDAQABAoIBAQDHG5RkqAYWv3DZ2SG2IpOmn7b2ZZRlCqGATKSt+XhGVJ4rAfy5HGwXUQ8ZKEcCAyPLyVBdn9ZZapgfvzd1FEoIVkmQ08kmA7XfQNZuWoO8xxOnIfAwx3FNyJ7W/0UPwPqbYJYAOh1X053SPnTL5/fm05b2irWI3cgbywkAogaES5gfKzoi8Bfj7TqMq+VS08XqWD9lbL7yL1hERqDRD4Nk6IStdqLZigFN2MK442yvVfpvl1aBFTJi06/0FVAugvaGtU/50AtJfssgnxkd7PvVAYYso1tEB2hnFq7CyeIeynfs28wREdEItCFe31U9oz17xte0FCHhYhNZmQkCnPd5AoGBAPMWmWqK2SfyaM0LEdx6tWAHkAftBrcO7Pu+8M+BLbp2l/GFBSSoOj1/oYKhOz9GDFulUBUeIbZ2h8w2vS95NEhe0jZoKhojs0jNF/rBcZLFMgcld4fVKZcLKxYiTfwh9Q1IiMmVgEkbLVuIkmZZNhN8tvf9SMa51e5hjVtPPaRnAoGBAPBfB0bTiPpNeWoE/W51nYwrrXVSMoy4JtBI9PObpcVzpy8t7AgWx/V7v6zK6V+kAeGMz9SbLmJSFG3dR+WCbsghXHbW1kWW2p6HhOmHrUF6KxoMN/5yENWeXfso9VhuF5QzoKg6yxhP7z1b49yCSWGEjEjWEDuSMB8ggTf4CQWbAoGADCH5oEaz1fmUX3+I8a8yNEvMVYjwB9z32QzLqh+xb5gRt11DR3QaDA29uu5fLaZKYZybpaIuXpQF7RxiTudGw8HvzgVe7JURkrWh18Ml7wRmndKx55atD7vf96fYqpfrSjFvmlga4gs4NVRYskELoOddnn0Gz9xgoBhAXOlUk0sCgYEA0njTHVBSa6F1A8FUy+jOyBLiso0D2DXTPqPzYG/Uin1HUcdrGnYgJrJx1nJiQK2SPBYZUTeEOPFYFA8jSjKYoEKd/S0GuC5sRU2ysu1rZp77qLY0PWdRmEswTaDCm+jiWpGORmAcv7AWcurILagjavEuCQTvd8n8uvSyUPitpasCgYA4dH5fy0vKnjX3nLdmnV8e9ezMSTlIGs2aN9jKhj+WPRD+rWSSC8KqduSRaJ729RZDiyTYv+7BAoX+4FVOfVycw0yT/I9GgMJV1l0a/lU7efv9lo1m16I6gM3oNYJq4vhEBMJoL+qNwNURk51oHojz7sU1nI4v5jyKhrkqPWrS9Q==';
  $alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5D9sH6/yqxjwoPYn2YuZ6O1aL1MYTwVpZTfu2j5FOh4qSZAtZs7iE+MMRTULrfmYhT+hmgfhhS9kSbiC/PHonELj2R7FlviKEzaXwqzfiEGhL7t3tKmhk3uec8oRmkWYwn9Nmu0MNyLIVJjjYQn3hcB1QheJOhxbtsGOHgPrNxXxOlZ26k8WsBF+nmLuL/Wba3umYRYEP++5q3y3VZtpcCAqde62nuETW8nc0CTA0K/cxHFP63a2LAmLUJNIUQazp692o5Vicv+OCgMzdYFr/BON9lxVjBnWIJkUasyQM7feLNJapiXv4TmtR7sIaFjYSvqaFSmo5gbFwxhkvieNXQIDAQAB';
  $app_id = '2016080500170362';
  $order['tran_no'] = gmtime();
  $order['alipay_account'] = "phbxnd6525@sandbox.com";
  $order['alipay_name'] = "沙箱环境";
  $order['total_amount'] = 10.00;

  $amount = $order['total_amount'] - $order['total_amount'] * $order['rate'] / 1000;
  $amount = round($amount, 2);

  $params = array(
    "out_biz_no" => $order['tran_no'],
    "payee_type" => "ALIPAY_LOGONID",
    "payee_account" => $order['alipay_account'],
    "amount" => $amount,
    "payer_show_name" => "单号:{$order['tran_no']}",
    "payee_real_name" => $order['alipay_name'],
    "remark" => "{$app['name']}收款"
  );

  Vendor('AlipaySdk.AopSdk');

  $aop = new \AopClient();
  $aop->gatewayUrl = $gatewayUrl;
  $aop->appId = $app_id;
  $aop->rsaPrivateKey=$rsaPrivateKey;
  $aop->alipayrsaPublicKey=$alipayrsaPublicKey;
  $aop->apiVersion = '1.0';
  $aop->signType = 'RSA2';
  $aop->postCharset='UTF-8';
  $aop->format='json';

  $request = new \AlipayFundTransToaccountTransferRequest();
  $request->setBizContent(json_encode($params));
  $result = $aop->execute($request);
  $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
  $resultCode = $result->$responseNode->code;

  if ($debug) {
    $json = json_encode($result->$responseNode);
    file_put_contents('alipay-debug.log', "alipay: {$json} \n", FILE_APPEND);
  }

  if (!empty($resultCode) && $resultCode == 10000) {
    $data['is_payed'] = 2;
    $data['updated_at'] = gmtime();
    $data['order_id'] = (string)$result->$responseNode->order_id;
    M('Orders')->field('id,order_id,updated_at,is_payed')->where("id={$order['id']}")->save($data);

    unset($data['is_payed']);
    $data['out_tran_no'] = $data['order_id'];
    unset($data['order_id']);
    $data['payed_at'] = $data['updated_at'];
    $data['payed_no'] = $order['alipay_account'];
    $data['payed_name'] = $order['alipay_name'];
    $data['status'] = 2;

    M('pay_logs')->where("order_id={$order['id']}")->save($data);
    return true;
  }

  return false;
}

function check_dailytask()
{
  $patch_log = M('dailytask_logs')->where("created_at=1500000000 and status=2")->find();
  if (!$patch_log) {
    $result = M('shops')->field('id as shop_id')->select();
    foreach ($result as $item) {
      if (!$item['shop_id']) {
        continue;
      }
      $added = M('amount_logs')
               ->where("status = 1 and shop_id={$item['shop_id']} ")
               ->sum("amount");
      !$added && !$added = 0;
      $drawed = M('amount_logs')
               ->where("status in (2,3) and shop_id={$item['shop_id']} ")
               ->sum("total_amount");
      !$drawed && $drawed = 0;
      $order_amount = M("Orders")->where("status in (2,4,5,7,9)  and shop_id={$item['shop_id']}")->sum("total_amount");
      !$order_amount && $order_amount = 0;
      $shop_update = array(
        'amount' => ($added - $drawed),
        'unbilled_amount' => ($order_amount - $added)
      );

      M('shops')->where("id={$item['shop_id']}")->save($shop_update);
    }
    $patch_log = array(
      'created_at' => 1500000000,
      'status' => 2
    );
    M('dailytask_logs')->add($patch_log);
  }
  $today = strtotime('today');
  $now_time = gmtime();
  $task_log = M('dailytask_logs')->where("created_at>=$today and status=1")->find();

  if (!$task_log) {
    //自动收货
    $where = "o.status = 4 and (({$now_time}-o.payed_at)/3600/24)>=a.receive_days";
    $sql = "UPDATE zjhj_wdds_orders o LEFT JOIN zjhj_wdds_shops s ON s.id = o.shop_id LEFT JOIN zjhj_wdds_apps a ON a.id = s.app_id";
    $sql .= " SET  o.status='5', o.picked_at='{$now_time}', o.updated_at='{$now_time}'";
    $sql .= "WHERE ({$where})";
    $result = M()->execute($sql);

    //自动完成
    $where = "o.status = 5 and (({$now_time}-o.picked_at)/3600/24)>=ap.aftersale_days";
    $result = M('orders')->alias('o')
             ->where($where)
             ->join("left join ".C('DB_PREFIX')."shops sp on sp.id = o.shop_id")
             ->join("left join ".C('DB_PREFIX')."apps ap on ap.id = sp.app_id")
             ->field('o.total_amount as total_amount, sp.id as shop_id, ap.id as app_id, sp.amount as shop_amount, o.id as order_id')
             ->select();

    foreach ($result as $item) {
     if (!$item['shop_id']) {
       continue;
     }
     #生成余额记录
     create_amount_log($item);
    }

    $sql = "UPDATE zjhj_wdds_orders o LEFT JOIN zjhj_wdds_shops sp ON sp.id = o.shop_id LEFT JOIN zjhj_wdds_apps ap ON ap.id = sp.app_id";
    $sql .= " SET  o.status='7', o.updated_at='{$now_time}'";
    $sql .= "WHERE ({$where})";
    $result = M()->execute($sql);

    $task_log = array(
      'created_at' => $now_time,
      'status' => 1
    );
    M('dailytask_logs')->add($task_log);
  }
}

function create_amount_log($item)
{
  $is_platform = M('orders')->where("id={$item['order_id']}")->getField('is_platform');
  if($is_platform == 1){
    create_brokerage_log($item);
    return true;
  }
  $today = strtotime('today');
  $now_time = gmtime();
  $check_log = M('amount_logs')->where("created_at>=$today and shop_id={$item['shop_id']} and status=1")->find();
  if($check_log) {
    $log_update = array(
      'amount' => $check_log['amount'] + $item['total_amount'],
      'updated_at' => $now_time
    );
    M('amount_logs')->where("id={$check_log['id']}")->save($log_update);
  } else {
    $amount_log = array(
      'app_id' => $item['app_id'],
      'shop_id' => $item['shop_id'],
      //'order_id' => $item['order_id'],
      'amount' => $item['total_amount'],
      'status' => 1,
      'created_at' => $now_time
    );
    M('amount_logs')->add($amount_log);
  }
  #更新用户余额
  $shop = M("Shops")->where("id = {$item['shop_id']}")->Field('unbilled_amount,amount')->find();
  $shop['unbilled_amount'] -= $item['total_amount'];
  $shop['amount'] += $item['total_amount'];
  $shop_update = array(
    'amount' => $shop['amount'],
    "unbilled_amount" => $shop['unbilled_amount'],
    'updated_at' => $now_time
  );
  M('shops')->where("id={$item['shop_id']}")->save($shop_update);
}

function refund_order($order)
{
  Vendor("Wxpay.WxPayApi");

  if ($order['status'] != 10 && $order['status']!=6) {
    return false;
  }
  $app_info = M('Apps')->where("id={$order['app_id']}")->find();

  $string = "{$app_info['wxpay_cert']}\r\n{$app_info['wxpay_key']}";
  $tempPemFile = tmpfile();
  fwrite($tempPemFile, $string);
  $tempPemPath = stream_get_meta_data($tempPemFile);
  $tempPemPath = $tempPemPath['uri'];

  $input = new \WxPayrefund();
  $input->SetAppid($app_info['cappid_applet']);
  $input->SetMch_id($app_info['mch_id']);

  $input->SetOut_trade_no($order['tran_no']);
  $input->SetOut_refund_no("r{$order['tran_no']}");
  $total_fee = $order['total_amount'] * 100;
  $input->SetTotal_fee($total_fee);
  $input->SetRefund_fee($total_fee);

  $input->SetKey($app_info['xcx_key']);

  $result = \WxPayApi::refund($input, 6, $tempPemPath);
  // file_put_contents('wechat-payment.log', $result);
  fclose($tempPemFile);

  return $result;
}

function upload_local_file($app_id, $file)
{
  if (!$app_id) {
    return false;
  }

  $storage_config = D('apps')->storage_config($app_id);
  switch ($storage_config['storage_type']) {
    case 1:
      $upload_config = array(
        'host' => $storage_config['upyun_host'],
        'bucket' => $storage_config['upyun_bucket'],
        'username' => $storage_config['upyun_username'],
        'password' => $storage_config['upyun_password'],
        'endpoint' => $storage_config['upyun_endpoint']
      );
      $upload_type = 'Upyun';
      $domain = $storage_config['upyun_endpoint'];
      $upload = new \Think\Upload\Driver\Upyun($upload_config);
      break;
    case 2:
      $upload_config = array(
        'AccessKeyId' => $storage_config['oss_key'],
        'AccessKeySecret' => $storage_config['oss_secret'],
        'domain' => $storage_config['oss_domain'],
        'Bucket' => $storage_config['oss_bucket'],
        'Endpoint' => $storage_config['oss_endpoint']
      );
      $upload_type = 'Aliyun';
      $domain = $storage_config['oss_domain'];
      $upload = new \Think\Upload\Driver\Aliyun($upload_config);
      break;
    case 3:
      $upload_config = array(
        'secretKey' => $storage_config['qiniu_secretkey'],
        'accessKey' => $storage_config['qiniu_accesskey'],
        'domain' => $storage_config['qiniu_domain'],
        'bucket' => $storage_config['qiniu_bucket'],
        'area' => $storage_config['qiniu_area']
      );
      $upload_type = 'Qiniu';
      $domain = $storage_config['qiniu_domain'];
      $upload = new \Think\Upload\Driver\Qiniu($upload_config);
      break;
  }

  $response = $upload->save($file);

  if ($upload_type != 'Aliyun' && $response) {
    $response = "$domain/{$file['savepath']}{$file['savename']}";
  }

  return $response;
}

function get_shop_wxacode($shop_id, $app_id)
{

  $xcx_token = load_xcx_token($app_id);

  $params = array(
    'path' => "/pages/share/share?shop_id=$shop_id&products_share=true"
  );

  ob_start();

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/wxa/getwxacode?access_token={$xcx_token['access_token']}");
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

  $response = curl_exec($ch);
  $filename = md5(uniqid()).'.png';
  $tmp_file = "upload/{$filename}";
  $result = file_put_contents($tmp_file, ob_get_contents());
  $check_result = json_decode(ob_get_contents(), true);
  curl_close($ch);
  ob_end_clean();

  if ($check_result['errcode']) {
    S('xcx_token_'.$app_id, NULL);
    $now_time = date("Y-m-d H:i:s",time());
    file_put_contents('wechat-token.log', "\r\n {$now_time} 商铺码调用xcx_token_{$app_id}:失效{$check_result['errcode']}{$check_result['errmsg']}", FILE_APPEND);
    return false;
  }

  $month = date('Ym');
  $file['savepath'] = "shops/wxacode/{$month}/";
  $file['savename'] = $filename;
  $file['tmp_name'] = $tmp_file;
  $file['type'] = 'image/png';
  $file['size'] = filesize(THINK_PATH."../{$tmp_file}");

  $img_url = upload_local_file($app_id, $file);

  @unlink($tmp_file);

  if ($img_url) {
    return $img_url;
  } else {
    return false;
  }
}

function wxpay_to_shop($log)
{
  Vendor("Wxpay.WxPayApi");

  $app_info = M('Apps')->where("id={$log['app_id']}")->find();

  $string = "{$app_info['wxpay_cert']}\r\n{$app_info['wxpay_key']}";
  $tempPemFile = tmpfile();
  fwrite($tempPemFile, $string);
  $tempPemPath = stream_get_meta_data($tempPemFile);
  $tempPemPath = $tempPemPath['uri'];

  $input = new \WxPaytoShop();
  $input->SetAppid($app_info['cappid_applet']);
  $input->SetMch_id($app_info['mch_id']);
  $input->SetOpenid($log['xcx_openid']);
  $input->SetCheck_name('FORCE_CHECK');
  $input->SetRe_user_name($log['truename']);
  $input->SetDesc("{$app_info['name']}收款");
  $input->SetPartner_trade_no($log['tran_no']);
  $amount = $log['amount'] * 100;
  $input->SetAmount($amount);

  $input->SetKey($app_info['xcx_key']);

  $result = \WxPayApi::wxpay($input, 6, $tempPemPath);
  //file_put_contents('wechat-payment.log', "\r\n".json_encode($result), FILE_APPEND);
  fclose($tempPemFile);

  return $result;
}

function create_brokerage_log($order)
{
  $now_time = gmtime();
  $products = M('order_children')
                ->where("order_id={$order['order_id']}")->select();
  $amount = 0;
  foreach ($products as $key => &$value) {
    $amount += ($value['product_price'] - $value['proxy_price']) * $value['product_num'];
  }

  $brokerage_log = array(
    'app_id' => $order['app_id'],
    'order_id' => $order['order_id'],
    'shop_id' => $order['shop_id'],
    'amount' => $amount,
    'created_at' => $now_time
  );
  M('brokerage_logs')->add($brokerage_log);

  #更新用户余额
  $shop_brokerage = M("Shops")->where("id = {$order['shop_id']}")->getField('brokerage');
  $shop_brokerage += $amount;
  $shop_update = array(
    'brokerage' => $shop_brokerage,
    'updated_at' => $now_time
  );
  M('shops')->where("id={$order['shop_id']}")->save($shop_update);
}


/**
 * [读取小程序token]
 * @return [type] [description]
 */
function load_xcx_token($app_id)
{
  /**
  *$app_key = M('apps')->where("id=$app_id")->getField('cappid_applet');
  *## 读取微擎中的token
  *$xcx_token = D('Common/token')->get_token($app_key);
  *if (!$xcx_token) {
  *  ## 读取缓存中的token
  *  $xcx_token = S('xcx_token_'.$app_id);
  *  if (!$xcx_token || !$xcx_token['access_token']) {
  *    $xcx_token = get_xcx_token($app_id);
  *  }
  *  $now_time = date("Y-m-d H:i:s",time());
  *  file_put_contents('wechat-token.log', "\r\n {$now_time} 读取缓存xcx_token_{$app_id}: {$xcx_token['access_token']}", FILE_APPEND);
  *}
  **/
  $xcx_token = S('xcx_token_'.$app_id);
  if (!$xcx_token || !$xcx_token['access_token']) {
    $xcx_token = get_xcx_token($app_id);
  }
  return $xcx_token;
}
/**
 * [获取小程序token]
 * @return [type] [description]
 */
function get_xcx_token($app_id)
{

  M()->startTrans();
  $app_info = M('apps')->lock(true)->where("id=$app_id")->find();
  if ($app_info) {
    $capp_id = $app_info['cappid_applet'];
    $capp_secret = $app_info['cappsecret_applet'];
    $endpoint = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$capp_id&secret=$capp_secret";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $endpoint);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    $response = curl_exec($ch);
    curl_close($ch);

    $response = json_decode($response, true);
    $now_time = date("Y-m-d H:i:s",time());

    if (!$response || !$response['access_token']) {
      file_put_contents('wechat-token.log', "\r\n {$now_time} 获取xcx_token_{$app_id}:失败{$response['errcode']}{$response['errmsg']}", FILE_APPEND);
      $result = false;
    } else {
      S('xcx_token_'.$app_id, $response, 7000);
      file_put_contents('wechat-token.log', "\r\n {$now_time} 获取xcx_token_{$app_id}:{$response['access_token']}", FILE_APPEND);
      $result = $response;
    }
  }

  M()->commit();
  return $result;
}

/**
 * [小程序消息模板]
 * @param  [type] $msg_obj [description]
 * @return [type]          [description]
 */
function send_app_msg($msg_obj, $app_id)
{
  if (!$msg_obj) {
    return false;
  }

  $xcx_token = load_xcx_token($app_id);

  $params = array(
    'touser' => $msg_obj['xcx_openid'],
    'template_id' => $msg_obj['template_id'],
    'form_id' => $msg_obj['form_id'],
    'data'=> $msg_obj['data'],
    'page' => $msg_obj['page']
  );

  $endpoint = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={$xcx_token['access_token']}";

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $endpoint);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));

  $response = curl_exec($ch);
  curl_close($ch);
  $response = json_decode($response, true);

  if (!$response) {
    return false;
  } else {
    if ($response['errcode'] && $response['errcode'] != 0) {
      if ($response['errcode'] != 0) S('xcx_token_'.$app_id, NULL);
      $now_time = date("Y-m-d H:i:s",time());
      file_put_contents('wechat-token.log', "\r\n {$now_time} 消息调用xcx_token_{$app_id}:失效{$msg_obj['template_id']}{$response['errcode']}{$response['errmsg']}", FILE_APPEND);
      return false;
    } else {
      return true;
    }
  }
}
